package com.example.admin.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.admin_model.entity.Employee;
import com.example.config.JwtConfig;
import com.example.admin.mapper.EmployeeMapper;
import com.example.admin.service.EmployeeService;
import com.example.exceptions.BusinessException;
import com.example.exceptions.enumetation.ResponseEnum;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author sjz
 * @since 2024-06-26
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Resource
    private JwtConfig jwtConfig;


    /**
     * 登录
     *
     * @param employee
     * @return
     */
    @Override
    public String login(Employee employee) {

        log.info("密码:{}", BCrypt.hashpw(employee.getPassword()));
        //构建条件查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee oneEmployee = getOne(wrapper);
        //判断结果
        if (oneEmployee == null) {
            //用户不存在
            log.info("用户:{}不存在", employee.getUsername());
            throw new BusinessException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        if (!BCrypt.checkpw(employee.getPassword(), oneEmployee.getPassword())) {
            //密码错误
            log.info("用户:{}的密码:{}错误", employee.getUsername(), employee.getPassword());
            throw new BusinessException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        //登录成功,下发令牌
        String token = JwtUtils.createJwt(
                oneEmployee.getId(),
                oneEmployee.getName(),
                null,
                jwtConfig.getTtl(),
                jwtConfig.getKey()
        );

        log.info("token:{}", token);
        return token;
    }

    @Override
    public String validate(String token) {

        log.info("token:{}", token);

        if (!JwtUtils.validateToken(token, jwtConfig.getKey())) {
            throw new RuntimeException("token失效");
        }

        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        return claims.get("adminId", String.class);
    }

}
